//
//  MessageViewController.m
//  huashiedu
//
//  Created by oceans on 2018/7/30.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "MessageViewController.h"
#import "OAuthAPI.h"
#import "MessageTableViewCell.h"
#import "HttpRequest.h"
#import "MessageModel.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import <RongIMKit/RongIMKit.h>
#import "MessageDetailViewController.h"

@interface MessageViewController () <UITableViewDelegate, UITableViewDataSource, RCIMReceiveMessageDelegate>

@property (strong, nonatomic) UITableView *tableview;
@property (strong, nonatomic) NSMutableArray <MessageModel *> *dataArr;
@property (strong, nonatomic) MetaModel *model;
@end

@implementation MessageViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        if ([OAuthAPI getAccessToken].length == 0) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"access_token_refresh" object:nil];
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshWhenLogout) name:@"klogin_notification" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refershView) name:@"refreshMessageList" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitedGroup:) name:@"exitGroup" object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"buy_class" object:nil];
    }
    return self;
}

- (void)exitedGroup:(NSNotification *)noti {
    
    int groupId = [noti.userInfo[@"groupId"] intValue];
    for (NSInteger i = 0; i < self.dataArr.count; i ++) {
        MessageModel *model = _dataArr[i];
        if (model._id == groupId) {
            [self.dataArr removeObject:model];
            [self.tableview reloadData];
            return;
        }
    }
}

- (void)refershView {
    [_tableview reloadData];
}

- (void)refreshWhenLogout {
    
    [self.dataArr removeAllObjects];
    [self.tableview.footer resetNoMoreData];
    [self.tableview reloadData];
    if ([OAuthAPI getAccessToken].length > 0) {
        [self loadData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArr = [NSMutableArray array];
    [self setupView];
    if ([OAuthAPI getAccessToken].length > 0) {
        [self loadData];
    }
    [self setupNavigation];
    
//    [HttpRequest getURL:@"http://huashi.api.emhome.cn/test/rongyun/join?id=1" paras:nil showProgress:NO successful:^(id  _Nullable result) {
//
//    } failed:^(int code, NSString *errMsg) {
//
//    }];
    
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
}

#pragma mark - 消息监听

- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    
    if (message.messageDirection == MessageDirection_RECEIVE) {
        [self receivedNewMessage:message];
    }
}

- (void)receivedNewMessage:(RCMessage*)message {
    
    __weak typeof(self) weakself = self;
    for (NSInteger i = 0; i < _dataArr.count; i ++) {
        MessageModel *model = _dataArr[i];
        if (model._id == [message.targetId intValue]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakself.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            });
            return;
        }
    }
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.tableview reloadData];
}

- (void)setupNavigation {
    self.tabBarController.navigationItem.leftBarButtonItem = nil;
    self.tabBarController.navigationItem.rightBarButtonItem = nil;
    self.tabBarController.navigationItem.titleView = nil;
    self.tabBarController.navigationItem.title = @"消息";
}

- (void)setupView {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - XNavigationHeight - XTabBarHeight) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [_tableview registerNib:[UINib nibWithNibName:@"MessageTableViewCell" bundle:nil] forCellReuseIdentifier:@"MessageTableViewCell"];
    _tableview.tableFooterView = [UIView new];
    [self.view addSubview:_tableview];
    _tableview.footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (void)loadData {
    
    if ([UserModel shared].hasLogin == NO) {
        return;
    }
    
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kmessage_list paras:nil showProgress:NO successful:^(id  _Nullable result) {
        [weakself.dataArr removeAllObjects];
        [weakself.tableview.footer resetNoMoreData];
        NSArray *array = result[@"data"][@"items"];
        for (NSDictionary *dic in array) {
            MessageModel *model = [[MessageModel alloc] initWithDic:dic];
            [weakself.dataArr addObject:model];
        }
        [weakself.tableview reloadData];
        MetaModel *model = [[MetaModel alloc] initWithDic:result[@"data"][@"meta"]];
        if (model.currentPage == model.pageCount || model.pageCount == 0) {
            [weakself.tableview.footer endRefreshingWithNoMoreData];
            weakself.model = nil;
        }else {
            weakself.model = model;
        }
    } failed:nil];
}

- (void)loadMoreData {
    
    __weak typeof(self) weakself = self;
    [HttpRequest getURL:kmessage_list paras:@{@"page": [NSNumber numberWithInt:_model.currentPage + 1]} showProgress:NO successful:^(id  _Nullable result) {
        
        NSArray *array = result[@"data"][@"items"];
        for (NSDictionary *dic in array) {
            MessageModel *model = [[MessageModel alloc] initWithDic:dic];
            [weakself.dataArr addObject:model];
        }
        [weakself.tableview reloadData];
        MetaModel *model = [[MetaModel alloc] initWithDic:result[@"data"][@"meta"]];
        weakself.model = model;
        if (model.currentPage == model.pageCount || model.pageCount == 0) {
            [weakself.tableview.footer endRefreshingWithNoMoreData];
        }else {
            [weakself.tableview.footer endRefreshing];
        }
    } failed:^(int code, NSString *errMsg) {
        [weakself.tableview.footer endRefreshing];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageTableViewCell"];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(MessageTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MessageModel *model = _dataArr[indexPath.row];
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.logo]];
    cell.nameLabel.text = [NSString stringWithFormat:@"%@（共%d人）", model.name, model.nums];
    [model loadLastMessage];
    if (model.draftString && model.draftString.length > 0) {
        cell.messageLabel.textColor = COLOR(235, 79, 115, 1);
        cell.messageLabel.text = [NSString stringWithFormat:@"[草稿]%@", model.draftString];
    }else if(model.message) {
        cell.messageLabel.textColor = COLOR(149, 149, 149, 1);
        NSString *userName = [model.message.content senderUserInfo].name;
        if ([model.message.content isKindOfClass:[RCTextMessage class]]) {
            RCTextMessage *messge = (RCTextMessage *)model.message.content;
            cell.messageLabel.text = [NSString stringWithFormat:@"%@:%@", userName, messge.content];
            NSLog(@"%@", [NSString stringWithFormat:@"%@:%@", userName, messge.content]);
        }else if ([model.message.content isKindOfClass:[RCImageMessage class]]) {
            cell.messageLabel.text = [NSString stringWithFormat:@"%@:[图片]", userName];
        }else if ([model.message.content isKindOfClass:[RCVoiceMessage class]]) {
            cell.messageLabel.text = [NSString stringWithFormat:@"%@:[语音]", userName];
        }else if ([model.message.content isKindOfClass:[RCLocationMessage class]]) {
            cell.messageLabel.text = [NSString stringWithFormat:@"%@:[位置]", userName];
        }else {
            cell.messageLabel.text = nil;
        }
    }else {
        cell.messageLabel.text = nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MessageModel *model = _dataArr[indexPath.row];
//    RCConversationViewController *conversationVC = [[RCConversationViewController alloc]init];
    MessageDetailViewController *conversationVC = [[MessageDetailViewController alloc] init];
    conversationVC.displayUserNameInCell = YES;
    conversationVC.conversationType = ConversationType_GROUP;
    conversationVC.targetId = [NSString stringWithFormat:@"%d", model._id];
    conversationVC.title = [NSString stringWithFormat:@"%@（共%d人）", model.name, model.nums];
    conversationVC.messageModel = model; [self.tabBarController.navigationController pushViewController:conversationVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
